package com.wondream.myframework.app.unipay.up;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by child on 2016/4/9.
 * <p>
 * AES 加密/解密
 */
@SuppressWarnings("restriction")
public class AESEncryptUtil {
    public static String encrypt(String content, String key) throws Exception {
        if (StringUtils.isBlank(content) || StringUtils.isBlank(key)) {
            return null;
        }

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(content.getBytes("utf-8"));
        return new BASE64Encoder().encode(bytes);
    }


    public static String decrypt(String content, String key) throws Exception {
        if (StringUtils.isBlank(content) || StringUtils.isBlank(key)) {
            return null;
        }

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = new BASE64Decoder().decodeBuffer(content);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }

    public static void main(String[] args) {
//        DES des = new DES(Mode.CBC, Padding.NoPadding, key, key);
    }

//    public static void main(String[] args) {
//        try {
//            String content = "helloworld";
//            String password = "98383025";
//            String result = encrypt(content, password);
//            System.out.println(result);
//            result = "B659377328B56DD4806EDFF5D8930AADB56848EBC063ECD7";
//            System.out.println(decrypt(result, password));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}